package com.atguigu.gmall.list.listener;

import com.atguigu.gmall.common.mqconstant.MqConst;
import com.atguigu.gmall.list.service.ListService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author wk
 * @create 2021-09-13 19:32
 * 消费消息  上下架 消息
 */
@Component
public class listListener {
    @Autowired
    private ListService listService;

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = MqConst.QUEUE_GOODS_UPPER, durable = "true", autoDelete = "false"),
                    exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS, durable = "true", autoDelete = "false"),
                    key = MqConst.ROUTING_GOODS_UPPER)})
    public void onSale(Channel channel, Long skuId, Message message) {
        try {
            listService.onSale(skuId);
            // 应答
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            if (!message.getMessageProperties().isRedelivered()) {
                // 如果不是第一次发送消息
                try {
                    // 则重新再发一次
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            } else {
                // 如果是生产者再次发送消息
                try {
                    channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = MqConst.QUEUE_GOODS_LOWER, durable = "true", autoDelete = "false"),
                    exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS),
                    key = MqConst.ROUTING_GOODS_LOWER)})
    public void onCancel(Channel channel, Long skuId, Message message) {
            // 应答
        try {
            listService.onCancel(skuId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
